package com.softer.ztb.service.impl;

import com.softer.ztb.common.entity.*;
import com.softer.ztb.common.enums.MessageEnum;
import com.softer.ztb.common.enums.ShiroResultEnum;
import com.softer.ztb.common.shiro.ShiroUtil;
import com.softer.ztb.entity.SysUser;
import com.softer.ztb.mapper.UserMapper;
import com.softer.ztb.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
/**
 * UserServiceImpl class
 * @author zcz
 * @date 2019/1/16
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ShiroCommonResult insertUser(SysUser user) {
        String salt = ShiroUtil.createSalt();
        String passWord = ShiroUtil.createPassWord(user.getPassWord(),salt);
        user.setSalt(salt);
        user.setPassWord(passWord);
        int i = userMapper.insert(user);
        if(i>0){
            return new ShiroCommonResult(ShiroResultEnum.SUCCESS.getCode(), MessageEnum.SUCCESS.getMsg());
        }
        return new ShiroCommonResult(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
    }

    @Override
    public ShiroCommonResult update(SysUser user) {
        if(null != user && StringUtils.isNotBlank(user.getPassWord())){
            String salt = ShiroUtil.createSalt();
            String passWord = ShiroUtil.createPassWord(user.getPassWord(),salt);
            user.setSalt(salt);
            user.setPassWord(passWord);
        }
        int i = userMapper.update(user);
        if(i>0){
            return new ShiroCommonResult(ShiroResultEnum.SUCCESS.getCode(), MessageEnum.SUCCESS.getMsg());
        }
        return new ShiroCommonResult(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
    }

    @Override
    public ShiroCommonResult delete(String id) {
        if(StringUtils.isNotBlank("id")){
            int i =  userMapper.delete(id);
            if(i>0){
                return new ShiroCommonResult(ShiroResultEnum.SUCCESS.getCode(), MessageEnum.SUCCESS.getMsg());
            }
        }
        return new ShiroCommonResult(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
    }


    @Override
    public ManagerPageResult getUserList(Page page, SysUser user) {
        ManagerPageResult mr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        page.setQueryBean(user);
        int count = userMapper.getCount(page);
        if (count > Integer.parseInt(Common.ZERO)) {
            List<SysUser> list = userMapper.getList(page);
            return mr.setResult(mr, jr, count, list);
        }
        return mr.setResult(mr, jr, Integer.parseInt(Common.ZERO), new ArrayList());

    }

}
